<!--
  数据包生成功能组件
  创建时间：2025-09-17
  作者：开发团队
  目的：实现数据包生成、下载和管理功能
-->

<template>
  <div class="data-package-generation">
    <el-card class="data-package-card">
      <template #header>
        <div class="card-header">
          <span>数据包生成</span>
        </div>
      </template>
      
      <el-form 
        :model="packageForm" 
        :rules="rules" 
        ref="packageFormRef" 
        label-width="120px"
        class="package-form"
      >
        <el-form-item label="数据类型" prop="contentTypes">
          <el-checkbox-group v-model="packageForm.contentTypes">
            <el-checkbox label="users">用户数据</el-checkbox>
            <el-checkbox label="visitors">访客数据</el-checkbox>
            <el-checkbox label="records">通行记录</el-checkbox>
            <el-checkbox label="admins">管理员数据</el-checkbox>
            <el-checkbox label="campuses">院区数据</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="加密选项" prop="encryption">
          <el-switch
            v-model="packageForm.encryption"
            active-text="启用加密"
            inactive-text="不加密"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="generatePackage" 
            :loading="generating"
            :disabled="packageForm.contentTypes.length === 0"
          >
            生成数据包
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="package-list-card">
      <template #header>
        <div class="card-header">
          <span>数据包列表</span>
          <el-button type="primary" @click="fetchPackages" :icon="Refresh">刷新</el-button>
        </div>
      </template>
      
      <el-table 
        :data="packages" 
        v-loading="loading"
        style="width: 100%"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content_types" label="数据类型" width="200">
          <template #default="scope">
            <el-tag 
              v-for="type in scope.row.content_types" 
              :key="type" 
              size="small" 
              style="margin-right: 5px"
            >
              {{ formatContentType(type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="file_size" label="文件大小" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="encryption_status" label="加密状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.encryption_status === 'encrypted' ? 'success' : 'info'">
              {{ scope.row.encryption_status === 'encrypted' ? '已加密' : '未加密' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="download_count" label="下载次数" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="downloadPackage(scope.row)"
              :loading="downloading[scope.row.id]"
            >
              下载
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deletePackage(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { superAdminApi } from '@/api/superadmin'
import type { DataPackage, DataPackageRequest } from '@/types/superadmin'
import { formatDate as formatDateUtil } from '@/utils/date'
import { showSuccess, showError, showInfo } from '@/utils/message'
import type { ApiResponse, PaginationResponse } from '@/types/common'

// 表单引用
const packageFormRef = ref<FormInstance>()

// 状态
const generating = ref(false)
const loading = ref(false)
const downloading = ref<Record<number, boolean>>({})

// 表单数据
const packageForm = reactive({
  contentTypes: [] as string[],
  encryption: true
})

// 表单验证规则
const rules = {
  contentTypes: [
    { required: true, message: '请选择至少一种数据类型', trigger: 'change' }
  ]
}

// 数据包列表
const packages = ref<DataPackage[]>([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

/**
 * 格式化内容类型显示
 * @param type 内容类型
 * @returns 显示名称
 */
const formatContentType = (type: string): string => {
  const typeMap: Record<string, string> = {
    users: '用户数据',
    visitors: '访客数据',
    records: '通行记录',
    admins: '管理员数据',
    campuses: '院区数据'
  }
  return typeMap[type] || type
}

/**
 * 格式化日期
 * @param dateStr 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateStr: string): string => {
  return formatDateUtil(dateStr)
}

/**
 * 格式化文件大小
 * @param bytes 文件大小（字节）
 * @returns 格式化后的文件大小
 */
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 生成数据包
 */
const generatePackage = async () => {
  if (!packageFormRef.value) return
  
  await packageFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      generating.value = true
      
      const requestData: DataPackageRequest = {
        content_types: packageForm.contentTypes,
        encryption: packageForm.encryption
      }
      
      const response = await superAdminApi.generateDataPackage(requestData)
      
      // 修复：正确访问响应数据 - response 是 Promise<ApiResponse<DataPackage>>
      // response.data 是 ApiResponse<DataPackage> 类型，包含 code, message, data 等属性
      if (response.data && (response.data as unknown as ApiResponse<DataPackage>).code === 200) {
        showSuccess('数据包生成成功')
        // 重新加载数据包列表
        await fetchPackages()
        // 重置表单
        packageForm.contentTypes = []
        packageForm.encryption = true
      } else {
        // 如果响应拦截器没有抛出错误，但code不是200，这里应该不会执行到
        // 因为响应拦截器会在code不是200时抛出错误
        showError('数据包生成失败')
      }
    } catch (error) {
      console.error('生成数据包失败:', error)
      showError('数据包生成失败')
    } finally {
      generating.value = false
    }
  })
}

/**
 * 获取数据包列表
 */
const fetchPackages = async () => {
  try {
    loading.value = true
    
    const response = await superAdminApi.getDataPackages({
      page: pagination.currentPage,
      size: pagination.pageSize
    })
    
    // 由于响应拦截器已经处理了响应格式，这里直接获取数据
    packages.value = response.items
    pagination.total = response.total
  } catch (error) {
    console.error('获取数据包列表失败:', error)
    showError('获取数据包列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 下载数据包
 * @param pkg 数据包信息
 */
const downloadPackage = async (pkg: DataPackage) => {
  try {
    downloading.value[pkg.id] = true
    
    // TODO: 实现数据包下载功能
    // 这里应该调用API获取下载链接或直接下载文件
    showInfo('下载功能待实现')
  } catch (error) {
    console.error('下载数据包失败:', error)
    showError('下载数据包失败')
  } finally {
    downloading.value[pkg.id] = false
  }
}

/**
 * 删除数据包
 * @param id 数据包ID
 */
const deletePackage = async (id: number) => {
  try {
    // TODO: 实现数据包删除功能
    showInfo('删除功能待实现')
  } catch (error) {
    console.error('删除数据包失败:', error)
    showError('删除数据包失败')
  }
}

/**
 * 处理分页大小变化
 * @param size 新的分页大小
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchPackages()
}

/**
 * 处理当前页变化
 * @param page 新的当前页
 */
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchPackages()
}

// 组件挂载时获取数据包列表
onMounted(() => {
  fetchPackages()
})
</script>

<style scoped>
.data-package-generation {
  padding: 20px;
}

.data-package-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.package-form {
  max-width: 600px;
}

.package-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>